package com.zhiyou.user.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhiyou.common.pojo.Result;
import com.zhiyou.user.pojo.User;
import com.zhiyou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    RedisTemplate redisTemplate;
    /**
     * 可上传图片、视频，只需在nginx配置中配置可识别的后缀
     */
    @PostMapping("/upload")
    public Result pictureUpload(@RequestParam(value = "file") MultipartFile uploadFile,Integer id){
        userService.updateImage(id,uploadFile);
        return new Result(true,200,"修改成功");
    }

    //发送短信验证码
    @PostMapping(value ="/security/{id}")
    public Result senSms(@PathVariable Integer id){

        userService.sendSms(id);
        return  new Result(true,200,"发送成功");
    }

    @RequestMapping(value ="/update" ,method = RequestMethod.POST)
    public Result regist(String code, User user){
        //1得到缓存中的验证码
        String chckcodeRedis = redisTemplate.opsForValue().get("checkcode_"+user.getId().toString()).equals(0)?null:(String) redisTemplate.opsForValue().get("checkcode_"+user.getId().toString());
        if(chckcodeRedis==null||chckcodeRedis.isEmpty()){
            return new Result(false,500,"请先获取验证码");
        }
        if(!chckcodeRedis.equals(code)){
            return new Result(false,500,"验证码错误");
        }
        userService.update(user);
        redisTemplate.opsForValue().set("checkcode_"+user.getId().toString(),0);
        return new Result(true,200,"修改成功");
    }


}
